package net.j4love.nio.channels;

import org.junit.Assert;
import org.junit.Test;

import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.util.Set;

/**
 * @author he peng
 * @create 2018/6/4 16:26
 * @see
 */
public class SelectorTest {

    @Test
    public void openTest() throws Exception {

        Selector selector = Selector.open();
        Assert.assertNotNull(selector);
        System.out.println("selector -> " + selector.getClass().getName());

        Assert.assertTrue(selector.isOpen());
    }

    @Test
    public void keysTest() throws Exception {
        Selector selector = Selector.open();
        Assert.assertNotNull(selector);
        System.out.println("selector -> " + selector.getClass().getName());

        Assert.assertTrue(selector.isOpen());
        System.out.println("keys -> " + selector.keys());
        System.out.println("selectedKeys -> " + selector.selectedKeys());
    }
    
    @Test
    public void selectTest() throws Exception {
        Selector selector = Selector.open();
        Assert.assertNotNull(selector);
        System.out.println("selector -> " + selector.getClass().getName());

        Assert.assertTrue(selector.isOpen());

        // select 会阻塞直到至少选择一个通道后返回
        int num = selector.select();

        System.out.println("selected num -> " + num);
    }

    @Test
    public void timeoutSelectTest() throws Exception {
        Selector selector = Selector.open();
        Assert.assertNotNull(selector);
        System.out.println("selector -> " + selector.getClass().getName());

        Assert.assertTrue(selector.isOpen());

        long st = System.currentTimeMillis();

        // 等待指定的时间 , 时间到了之后无论有没有选中的通道都会返回
        int num = selector.select(3000);

        System.out.println("selected num -> " + num + " , select time = " + (System.currentTimeMillis() - st) + " ms");
    }

    @Test
    public void selectNowTest() throws Exception {
        Selector selector = Selector.open();
        Assert.assertNotNull(selector);
        System.out.println("selector -> " + selector.getClass().getName());

        Assert.assertTrue(selector.isOpen());

        long st = System.nanoTime();

        // 无阻塞
        int num = selector.selectNow();

        System.out.println("selected num -> " + num + " , select time = " + (System.nanoTime() - st) + " ns");
    }
}
